package com.linyx.simpleboot.zookeeper.LeaderLatch;

import java.io.IOException;

import javax.annotation.PostConstruct;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.InitBinder;

import com.linyx.simpleboot.schedule.ScheduledTasks;

//@Component
public class MyLeaderLatch {
	
	private static final Logger log = LoggerFactory.getLogger(MyLeaderLatch.class);
	
	private static final String PATH = "/leader";
	private LeaderLatch latch;
	
	
//	@PostConstruct
    public  void init(){
		log.info("开始初始化");
		 RetryPolicy rp = new ExponentialBackoffRetry(1000, 3);
		  
		  CuratorFramework client = CuratorFrameworkFactory.builder()
			        .connectString("127.0.0.1:2181")
			        .sessionTimeoutMs(1000000)
			        .connectionTimeoutMs(30000)
			        .retryPolicy(rp)
			        .build();
		  client.start();
		 
		  
		  latch = new LeaderLatch(client, PATH);	
		 start();
		  log.info("初始化完毕");
	}
	
	  public  void start(){
		  
		  try {
			this.latch.start();
			log.info("启动 latch 成功");
		} catch (Exception e) {
			log.error("启动 latch 失败",e);
		}
		  
	  }
	  public  void close(){
		  try {
			this.latch.close();
			log.info("关闭 latch 成功");
		} catch (IOException e) {
			log.error("关闭 latch 失败",e);
		}
		  
	  }
	  
	  public  boolean hasLeadership(){
		  
		  return this.latch.hasLeadership();
		  
		  
	  }

}
